﻿using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using HZ.Supervise.IBLL;
using HZ.Supervise.Model;
using HZ.Supervise.Model.Enum;

public partial class Hospital_MothStatistics : BasePage
{
    public Hospital_MothStatistics()
    {
        this.ModuleNo = Module.医院统计分析.ToString();
        this.PageOperateType = OperateType.医院月采购量信息统计.ToString();
    }
    protected void Page_Load(object sender, EventArgs e)
    {
        QueryControl1.OnQueryClick += new EventHandler(QueryControl1_OnQueryClick);
        if (!this.IsPostBack)
        {
            ViewState["query"] = URLUtil.GetSuperviseQueryFromURL(Request);
            QueryControl1.BindDataPre((SuperviseQuery)ViewState["query"]);//绑定查询条件的一些数据源 质量层次等
            BindData();
            QueryControl1.BindSort(gvwInfo);
            GetMonthCount();
        }
    }

    void QueryControl1_OnQueryClick(object sender, EventArgs e)
    {
        AspNetPager1.CurrentPageIndex = 1;
        ViewState["query"] = QueryControl1.UpdateQueryFromValue((SuperviseQuery)ViewState["query"]);
        BindData();
        GetMonthCount();
    }


    //绑定数据源
    private void BindData()
    {
        int t = 0;

        HZ.Supervise.IBLL.IExecuteContext ie = HZ.Supervise.BLLFactory.ExecuteContext();
        ie.QueryObject = new HZ.Supervise.Model.QueryObject()
        {
            //分组字段
            GroupField = GroupByField.PurchaseTimeMonth,
            //查询条件
            Query = (SuperviseQuery)ViewState["query"],
            //分组查询字段
            GroupSelectField = GroupFields.PurchaseAmountTotal | GroupFields.WareHouseRate | GroupFields.WareHouseAmountTotal | GroupFields.DistributeAmountTotal | GroupFields.DistributeRate,
            //排序字段
            SortField = QueryControl1.SortField == "" ? "PurchaseTimeMonth ASC" : QueryControl1.SortField
        };

        //将数据填入gridview中
        System.Data.DataTable dt = ie.ExecutePage(AspNetPager1.CurrentPageIndex, AspNetPager1.PageSize, out t);
        AspNetPager1.RecordCount = t;
        //显示相应的字段
        GridViewUtil.AdjustGridView(gvwInfo, dt);

        gvwInfo.DataSource = dt;
        gvwInfo.DataBind();
        setChart(dt);
        SetColumnVisible();

    }


    /// <summary>

    /// <summary>
    /// 屏蔽相关查询连接
    /// </summary>
    private void SetColumnVisible()
    {

        if (!string.IsNullOrEmpty(QueryControl1.CompanyID_PS))
        {
            foreach (GridViewRow row in gvwInfo.Rows)
            {
                row.FindControl("lbnCom_PS").Visible = false;
            }
        }
        if (!string.IsNullOrEmpty(QueryControl1.HospitalID))
        {
            foreach (GridViewRow row in gvwInfo.Rows)
            {
                row.FindControl("lbnHos").Visible = false;
            }
        }
    }
    
    protected void btnQuery_Click(object sender, EventArgs e)
    {
        BindData();
    }
   
    
    protected void AspNetPager1_PageChanged1(object sender, EventArgs e)
    {
        BindData();
    }
    protected void gvwInfo_RowCommand(object sender, GridViewCommandEventArgs e)
    {
        if (e.CommandName == "Hospital")
        {
            //设置分组查询字段GroupSelectField
            //if (ShowColumns.ShowColumn == null)
            //{
            //    ShowColumns.ShowColumn = new ShowColumns();
            //}
            //ShowColumns.ShowColumn.GroupFields = GroupFields.DistributeCountTotal | GroupFields.DistributeRate | GroupFields.PurchaseCountTotal | GroupFields.WareHouseCountTotal;

            if (!string.IsNullOrEmpty(e.CommandArgument.ToString()))
            {
                getTimeConversion(e.CommandArgument.ToString());
                string sessionid = Guid.NewGuid().ToString();
                SuperviseQuery query = (SuperviseQuery)ViewState["query"];
                //query.StartTimeFrom = MonthStartTime;
                //query.StartTimeTo = MonthEndTime;
                query.PlanTimeFrom = MonthStartTime;
                query.PlanTimeTo = MonthEndTime;
                query._QueryPrompt=query._QueryPrompt+" "+e.CommandArgument.ToString();

                Session[sessionid] = query;
                string url = System.Configuration.ConfigurationManager.AppSettings["HospitalID"];
                Response.Redirect(string.Format("{0}?sessionid={1}", url, sessionid));
            }
        }

        if (e.CommandName == "Company")
        {
            if (!string.IsNullOrEmpty(e.CommandArgument.ToString()))
            {
                getTimeConversion(e.CommandArgument.ToString());
                string sessionid = Guid.NewGuid().ToString();
                SuperviseQuery query = (SuperviseQuery)ViewState["query"];
                //query.StartTimeFrom = MonthStartTime;
                //query.StartTimeTo = MonthEndTime;
                query.PlanTimeFrom = MonthStartTime;
                query.PlanTimeTo = MonthEndTime;
                query._QueryPrompt = query._QueryPrompt + " " + e.CommandArgument.ToString();

                Session[sessionid] = query;
                string url = System.Configuration.ConfigurationManager.AppSettings["CompanyID_PS"];
                Response.Redirect(string.Format("{0}?sessionid={1}", url, sessionid));
            }
        }

        if (e.CommandName == "Drugs")
        {
            if (!string.IsNullOrEmpty(e.CommandArgument.ToString()))
            {
                getTimeConversion(e.CommandArgument.ToString());
                string sessionid = Guid.NewGuid().ToString();
                SuperviseQuery query = (SuperviseQuery)ViewState["query"];
                //query.StartTimeFrom = MonthStartTime;
                //query.StartTimeTo = MonthEndTime;
                query.PlanTimeFrom = MonthStartTime;
                query.PlanTimeTo = MonthEndTime;
                query._QueryPrompt = query._QueryPrompt + " " + e.CommandArgument.ToString();

                Session[sessionid] = query;
                string url = System.Configuration.ConfigurationManager.AppSettings["ProcureCatalogID"];
                Response.Redirect(string.Format("{0}?sessionid={1}", url, sessionid));
            }
        }
    }

    DateTime MonthStartTime;
    DateTime MonthEndTime;
    private void getTimeConversion(string _values)
    {
        string _Year = _values.Substring(0, 4);
        string _Month = _values.Substring(4, 2);

        MonthStartTime = DateTime.Parse(_Year + "-" + _Month + "-01");

        MonthEndTime = DateTime.Parse(_Year + "-" + _Month + "-" + System.DateTime.DaysInMonth(int.Parse(_Year),int.Parse(_Month)).ToString()).AddDays(1);
    }


    protected void ddlOther_SelectedIndexChanged(object sender, EventArgs e)
    {
        string stkey = "";
        string sessionid = string.Empty;
        GridViewRow row = (GridViewRow)((Control)sender).Parent.Parent;
        DropDownList ddl = (DropDownList)row.FindControl("ddlOther");
        stkey = ddl.SelectedValue;
        getTimeConversion(row.Cells[1].Text);
        if (stkey != "")
        {
            sessionid = Guid.NewGuid().ToString();
            SuperviseQuery query = (SuperviseQuery)ViewState["query"];
            //赋予当前行的主键值
            //query.StartTimeFrom = MonthStartTime;
            //query.StartTimeTo = MonthEndTime;
            query.PlanTimeFrom = MonthStartTime;
            query.PlanTimeTo = MonthEndTime;
            query._QueryPrompt = query._QueryPrompt + " " + gvwInfo.DataKeys[row.RowIndex].Value;

            Session[sessionid] = query;
            string url = System.Configuration.ConfigurationManager.AppSettings[stkey];
            Response.Redirect(string.Format("{0}?sessionid={1}", url, sessionid));
        }
    }

    /// <summary>
    /// 设置图表
    /// </summary>
    /// <param name="?"></param>
    private void setChart(System.Data.DataTable dt)
    {
        if (dt.Rows.Count > 0)
        {
            this.ChartControl1.Visible = false;
            HZ.Supervise.Web.WebService.ChartConfig serChart = new HZ.Supervise.Web.WebService.ChartConfig();
            dt.TableName = "月统计";
            serChart.DataSource = dt;
            serChart.XName = "PurchaseTimeMonth";
            serChart.YNames = "PurchaseAmountTotal";

            if (ShowColumns.ShowColumn == null)
            {
                serChart.XName = "PurchaseTimeMonth";
                serChart.YNames = "PurchaseAmountTotal";
            }
            else
            {
                string[] _columns = ShowColumns.ShowColumn.GroupFields.ToString().Split(',');
                serChart.XName = "PurchaseTimeMonth";
                serChart.YNames = _columns[0];
            }

            serChart.ChartTypes = HZ.Supervise.Web.WebService.ChartType.ColumnChart;

            ChartControl1.webChart = serChart;
            ChartControl1.PageId = Guid.NewGuid().ToString();
            ChartControl1.EntranceChart();
        }
        else
        {
            ChartControl1.Visible = false;
        }
    }
    protected void lbtnSee_Click(object sender, EventArgs e)
    {
        if (this.lbtnSee.Text == "显示图表")
        {
            ChartControl1.Visible = true;
            this.lbtnSee.Text = "隐藏图表";
        }
        else
        {
            ChartControl1.Visible = false;
            this.lbtnSee.Text = "显示图表";
        }
    }
    public void GetMonthCount()
    {
        int t = 0;

        HZ.Supervise.IBLL.IExecuteContext ie = HZ.Supervise.BLLFactory.ExecuteContext();
        ie.QueryObject = new HZ.Supervise.Model.QueryObject()
        {
            //分组字段
            GroupField = GroupByField.PurchaseTimeMonth,
            //查询条件
            Query = (SuperviseQuery)ViewState["query"],
            //分组查询字段
            GroupSelectField = GroupFields.PurchaseAmountTotal | GroupFields.WareHouseRate | GroupFields.WareHouseAmountTotal | GroupFields.DistributeAmountTotal | GroupFields.DistributeRate,
            //排序字段
            SortField = QueryControl1.SortField == "" ? "PurchaseTimeMonth ASC" : QueryControl1.SortField
        };

        
        System.Data.DataTable dt = ie.ExecutePage(1,0, out t);
        double PurchaseAmountTotal = 0;//采购总金额
        double DistributeAmountTotal = 0;//配送总金额
        double WareHouseAmountTotal = 0; //入库总金额

        if (dt.Rows.Count>0)
        {
            for (int i = 0; i < dt.Rows.Count;i++ )
            {

                PurchaseAmountTotal += HZ.MathUtil.SToF(dt.Rows[i]["PurchaseAmountTotal"].ToString());
                DistributeAmountTotal += HZ.MathUtil.SToF(dt.Rows[i]["DistributeAmountTotal"].ToString());
                WareHouseAmountTotal += HZ.MathUtil.SToF(dt.Rows[i]["WareHouseAmountTotal"].ToString());
            }

            lblCount.Text = "采购总金额为:" + PurchaseAmountTotal.ToString("N2") + ";配送总金额为:" + DistributeAmountTotal.ToString("N2") + ";入库总金额为:" + WareHouseAmountTotal.ToString("N2") + "";
        }
        else
        {
            lblCount.Text = "暂无符合条件的数据！";
        }
    }
}
